import logging
from google.appengine.ext import db
import xmlobjects
from MarkupTools import delete_invalid_xml_tags
from xml.etree.cElementTree import ParseError


class XMLProperty(db.TextProperty):
  def __init__(self, root_element=None, *args, **kwargs):
    self.root_element = root_element

    super(XMLProperty, self).__init__(*args, **kwargs)

  def __set__(self, model_instance, value):
    value = self.validate(value)
    xml = None
    if value:
      value = delete_invalid_xml_tags(value)
      try:
        xml = xmlobjects.fromstring(value)
      except ParseError as e:
        logging.error("XML ParseError caused by '''%s'''" % value)
        logging.exception(e)
        return
    if not xml and self.root_element:
      xml = xmlobjects.XMLObject(self.root_element)
    setattr(model_instance, self._attr_name(), xml)

  def get_value_for_datastore(self, model_instance):
    return db.Text(unicode(super(XMLProperty, self).get_value_for_datastore(model_instance)))
